package com.cws.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.cws.business.ILoginBusiness;
import com.cws.business.IUserBusiness;
import com.cws.model.User;
import com.cws.web.UserSession;


@Controller
public class LoginController extends BaseController{
	
	@Autowired
	private ILoginBusiness loginBusiness;
	
	@Autowired
	private IUserBusiness userBusiness;
	
	@RequestMapping("/index")
	public ModelAndView index(HttpServletRequest request){
		HttpSession session = request.getSession();
		UserSession userSession = (UserSession) session.getAttribute(UserSession.USER_SESSION_KEY);
		ModelAndView mv = new ModelAndView("index");
		 mv.addObject("aaa", "accca");
        return mv;
	}
	
	
	 @RequestMapping("/ajax/loginPage")
     public ModelAndView Login(HttpServletRequest request){
		 ModelAndView mv = new ModelAndView("jsp/user/login");
		 mv.addObject("aaa", "accca");
         return mv;
     }
	 @ResponseBody  
	 @RequestMapping("/login")
     public Map<String, Object> Login(@RequestParam(value = "loginId",required = true) String loginId,@RequestParam(value = "password",required = true) String password,@RequestParam(value = "kaptcha",required = true) String kaptcha, HttpServletRequest request){
		 Map<String, Object> modelMap = new HashMap<String, Object>();
		 HttpSession session = request.getSession();
		 String kaptchaExpected = (String)session.getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
		 User user = loginBusiness.getUser(loginId, password);
		 boolean status = (user != null)&&kaptchaExpected.equalsIgnoreCase(kaptcha);
		 if(status){
			 UserSession userSession = new UserSession(loginId,user.getUserId());
			 session.setAttribute(UserSession.USER_SESSION_KEY, userSession);
			 setUserSession(request,userSession);
		 }
		modelMap.put("status",status);//
		modelMap.put("data", new Date());
		return modelMap;

     }
	 
	 
	 
	 
	
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
}
